// 项目详情页JavaScript功能

// 返回列表页
function goBack() {
    window.location.href = '/dashboard';
}

// 加载项目详情数据
async function loadProjectDetail(period, project) {
    try {
        const params = new URLSearchParams({
            period: period,
            project: project
        });
        
        const response = await fetch(`/api/project-detail?${params}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 更新项目概览信息
        updateProjectOverview(data.project_info);
        
        // 更新角色统计
        updateRoleStats(data.project_info.role_stats, data.project_info.total_worktime);
        
        // 更新系统详情
        updateSystemsDetails(data.systems, data.systems_details);
        
    } catch (error) {
        console.error('加载项目详情失败:', error);
        showMessage('加载项目详情失败: ' + error.message, 'error');
    }
}

// 更新项目概览信息
function updateProjectOverview(projectInfo) {
    const displayProjectName = projectInfo.project_name || '未指定项目';
    
    document.getElementById('statistics-period').textContent = projectInfo.statistics_period;
    document.getElementById('project-name').textContent = displayProjectName;
    document.getElementById('total-systems').textContent = projectInfo.total_systems;
    document.getElementById('total-requirements').textContent = projectInfo.total_requirements;
    document.getElementById('total-worktime').textContent = projectInfo.total_worktime.toFixed(1) + ' 人天';
    document.getElementById('total-roles').textContent = projectInfo.total_roles;
    
    // 更新页面标题
    document.getElementById('project-title').textContent = `${displayProjectName} - 工时统计详情`;
}

// 更新角色统计
function updateRoleStats(roleStats, totalWorktime) {
    const tbody = document.getElementById('role-stats-tbody');
    tbody.innerHTML = '';
    
    roleStats.forEach(role => {
        const percentage = totalWorktime > 0 ? ((role.worktime / totalWorktime) * 100).toFixed(1) : 0;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${role.role}</td>
            <td>${role.person_count}</td>
            <td>${role.worktime.toFixed(1)} 人天</td>
            <td>${percentage}%</td>
        `;
        tbody.appendChild(row);
    });
    
    if (roleStats.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #6c757d;">暂无角色统计数据</td></tr>';
    }
}

// 更新系统详情
function updateSystemsDetails(systems, systemsDetails) {
    const container = document.getElementById('systems-container');
    container.innerHTML = '';
    
    systems.forEach(system => {
        const systemDetail = systemsDetails[system.system_name] || {
            requirements: [],
            requirement_names: [],
            requirement_count: 0,
            roles: [],
            role_count: 0
        };
        
        // 创建系统卡片
        const systemCard = document.createElement('div');
        systemCard.className = 'system-card';
        
        // 系统基本信息
        const systemHeader = document.createElement('div');
        systemHeader.className = 'system-header';
        systemHeader.innerHTML = `
            <h4>${system.system_name || '未指定系统'}</h4>
            <div class="system-stats">
                <span class="stat-item">需求数: ${system.total_requirements}</span>
                <span class="stat-item">工时: ${system.total_worktime.toFixed(1)} 人天</span>
                <span class="stat-item">角色数: ${systemDetail.role_count}</span>
            </div>
        `;
        
        // 需求名称列表
        const requirementsList = document.createElement('div');
        requirementsList.className = 'requirements-list';
        requirementsList.innerHTML = `
            <h5>需求列表 (${systemDetail.requirement_count}个)</h5>
            <div class="requirements-tags">
                ${systemDetail.requirement_names.map(name => 
                    `<span class="requirement-tag">${name}</span>`
                ).join('')}
            </div>
        `;
        
        // 人员工时详情表格
        const detailTable = document.createElement('div');
        detailTable.className = 'detail-table-container';
        
        // 按需求分组显示人员工时
        const requirementGroups = groupRequirementsByContent(systemDetail.requirements);
        
        let tableHTML = `
            <h5>人员工时详情</h5>
            <div class="requirements-detail">
        `;
        
        Object.keys(requirementGroups).forEach(requirementContent => {
            const reqGroup = requirementGroups[requirementContent];
            const totalReqWorktime = reqGroup.reduce((sum, req) => sum + req.worktime, 0);
            
            tableHTML += `
                <div class="requirement-group">
                    <div class="requirement-header">
                        <strong>${requirementContent}</strong>
                        <span class="requirement-worktime">总工时: ${totalReqWorktime.toFixed(1)} 人天</span>
                    </div>
                    <table class="data-table requirement-table">
                        <thead>
                            <tr>
                                <th>人员姓名</th>
                                <th>角色</th>
                                <th>工时</th>
                                <th>需求类型</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            reqGroup.forEach(req => {
                tableHTML += `
                    <tr>
                        <td>${req.person_name}</td>
                        <td>${req.person_role}</td>
                        <td>${req.worktime.toFixed(1)} 人天</td>
                        <td>${req.requirement_type}</td>
                        <td><span class="status-badge status-${getStatusClass(req.status)}">${req.status}</span></td>
                    </tr>
                `;
            });
            
            tableHTML += `
                        </tbody>
                    </table>
                </div>
            `;
        });
        
        tableHTML += '</div>';
        detailTable.innerHTML = tableHTML;
        
        // 组装系统卡片
        systemCard.appendChild(systemHeader);
        systemCard.appendChild(requirementsList);
        systemCard.appendChild(detailTable);
        
        container.appendChild(systemCard);
    });
    
    if (systems.length === 0) {
        container.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 20px;">暂无系统数据</div>';
    }
}

// 按需求内容分组
function groupRequirementsByContent(requirements) {
    const groups = {};
    
    requirements.forEach(req => {
        const content = req.work_content || '未指定需求';
        if (!groups[content]) {
            groups[content] = [];
        }
        groups[content].push(req);
    });
    
    return groups;
}

// 获取状态样式类
function getStatusClass(status) {
    if (!status) return 'default';
    
    const statusStr = status.toLowerCase();
    if (statusStr.includes('完成') || statusStr.includes('上线')) {
        return 'completed';
    } else if (statusStr.includes('进行') || statusStr.includes('开发')) {
        return 'in-progress';
    } else {
        return 'default';
    }
}

// 显示消息提示
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 10px 20px;
        border-radius: 4px;
        color: white;
        z-index: 1000;
        ${type === 'error' ? 'background-color: #dc3545;' : 'background-color: #28a745;'}
    `;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}